import { CarRowState } from "../car/carReducer"

interface UserState {
	addressList: AddressState[],
	avator: string,
	id: string,
	nickname: string,
	orderList: OrderDetail[],
	token: string,
	username: string
}

interface AddressState {
	nickname: string
	tel: string
	address: string
}

export type OrderState = '待付款' | '待收货' | '退换/售后' | '已关闭'

export interface OrderDetail {
	id: string,
	price: number,
	title: string,
	addressDetail: AddressState,
	createDateTime: number,
	projects: CarRowState[],
	state: OrderState
}

const initState: UserState = {
	avator: '',
	id: '',
	nickname: '',
	token: '',
	username: '',

	addressList: [],
	orderList: [],
}

const LOGINSUCCESS = 'LOGINSUCCESS'
const QUITLOGIN = 'QUITLOGIN'
const CREATEORDER = 'CREATEORDER'
const TRADESUCCESS = 'TRADESUCCESS'


interface TradeSuccessAction {
	type: typeof TRADESUCCESS
	payload: string
}
export function tradeSuccessActionCreator(payload: string): TradeSuccessAction {
	return { type: TRADESUCCESS, payload }
}


interface CreateOrderAction {
	type: typeof CREATEORDER
	payload: OrderDetail
}

export function createOrderActionCreator(payload: OrderDetail): CreateOrderAction {
	return { type: CREATEORDER, payload }
}


interface LoginSuccessAction {
	type: typeof LOGINSUCCESS
	payload: UserState
}

export function loginSuccessActionCreator(payload: UserState): LoginSuccessAction {
	return { type: LOGINSUCCESS, payload }
}

interface QuitLoginAction {
	type: typeof QUITLOGIN
}

export function quitLoginActionCreator(): QuitLoginAction {
	return { type: QUITLOGIN }
}


type CarAction = LoginSuccessAction | QuitLoginAction | CreateOrderAction | TradeSuccessAction

const userReducer = (state = initState, action: CarAction): UserState => {
	const { type } = action
	switch (type) {
		case LOGINSUCCESS: {
			return {
				...state,
				...action.payload
			}
		}
		case QUITLOGIN: {
			return {
				addressList: [],
				avator: '',
				id: '',
				nickname: '',
				orderList: [],
				token: '',
				username: ''
			}
		}
		case CREATEORDER: {
			return {
				...state,
				orderList: [action.payload, ...state.orderList]
			}
		}
		case TRADESUCCESS: {
			const item = state.orderList.find(v => v.id === action.payload);
			if (item) {
				item.state = '待收货'
			}
			return {
				...state,
				orderList: [...state.orderList]
			}
		}
		default: return state
	}
}


export default userReducer